package sun.jj.a33test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

import cn.rervision.usbcamera.USBCamera;


public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private USBCamera mCamera;
    private SurfaceView mSurfaceView;

    private Button mBtnSwitch, mBtnPhoto,mBtnRecord;


    private int exposure_v,contrast_v,luminance_v,whitebalance_v;
    private int[] mLuminances,mContrasts,mExposures,mWhiteBalances;
    private  String[] mSupportedSizes;
    private  String mPhotoSize;
    private ListView mListView;
    private ArrayAdapter<String> mArrayAdapter;


    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what ==1){
                if(mCamera.isOpened()){
                    mCamera.takePicture(mPhotoSize);
                }
            }
        }
    };

    USBCamera.OnDeviceOperateListener mOnDeviceOperateListener = new USBCamera.OnDeviceOperateListener(){

        @Override
        public void onOpen() {
            if(mCamera.isOpened()){

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSupportedSizes= mCamera.getSupportedSizes();
                        if(mSupportedSizes != null){
                            mArrayAdapter.clear();
                            mArrayAdapter.addAll(mSupportedSizes);
                        }

                        mBtnSwitch.setText(" 开 ");
                    }
                });
            }
        }

        @Override
        public void onClose() {
            if(!mCamera.isOpened()){
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBtnSwitch.setText(" 关 ");
                    }
                });
            }
        }

        @Override
        public void onRestart() {

        }

        @Override
        public void onStartRecord() {

        }

        @Override
        public void onStopRecord() {

        }

        @Override
        public void onTakePicture(String path) {
            Log.d(TAG,"take pidture success "+path);

            //mHandler.sendEmptyMessageDelayed(1,1000);
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.DEVICE.contains("clover")){

        }
        mCamera = USBCamera.getInstance();
        setContentView(R.layout.activity_main);

        mSurfaceView=(SurfaceView)findViewById(R.id.lay_preview);
        mSurfaceView.getHolder().addCallback(mSurfaceCallback);

        mListView= (ListView) findViewById(R.id.lv_sizes);
        mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        mArrayAdapter = new ArrayAdapter<String>(this, R.layout.listview_item_style, new ArrayList<String>());
        mListView.setAdapter(mArrayAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Log.d(TAG, "onItemClick " + position +" -- "+ id);
                if(mSupportedSizes != null){
                    mPhotoSize=mSupportedSizes[position];
                    Log.d(TAG, "mPhotoSize " + mPhotoSize );
                }
            }
        });

        mBtnSwitch=(Button)findViewById(R.id.btn_switch);
        mBtnSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mBtnSwitch.setEnabled(false);

                if (!mCamera.isOpened()) {

                    mCamera.open("video0");
                }else {
                    mCamera.close();
                }

                mBtnSwitch.setEnabled(true);
            }
        });

        mBtnPhoto =(Button)findViewById(R.id.btn_photo);
        mBtnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!mCamera.isOpened()) {
                    Toast.makeText(MainActivity.this,"please start camera!",Toast.LENGTH_SHORT).show();
                    return;
                }
                mBtnPhoto.setEnabled(false);
                mCamera.takePicture(mPhotoSize);
                mBtnPhoto.setEnabled(true);
            }
        });

        mBtnRecord = (Button)findViewById(R.id.btn_record);
        mBtnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!mCamera.isOpened()) {
                    Toast.makeText(MainActivity.this, "please start camera!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!mCamera.isRecorded()) {
                    mCamera.startRecord();
                } else {
                    mCamera.stopRecord();
                }

                mBtnRecord.setTextColor(mCamera.isRecorded()?Color.RED:Color.WHITE);
            }
        });

        mCamera.setDeviceOperateListener(mOnDeviceOperateListener);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCamera.setDeviceOperateListener(null);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
            .setNegativeButton("后台运行", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intent);
                }
            }).setPositiveButton("完全退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (mCamera.isRecorded()) {
                        mCamera.stopRecord();
                    }

                    if (mCamera.isOpened()){
                        mCamera.close();
                    }
                    finish();
                }
            }).show();
    }

    private final SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback(){
        private Surface mSurface;
        @Override
        public void surfaceCreated(SurfaceHolder holder) {

        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            mSurface = holder.getSurface();
            USBCamera.nativeStartPreview(mSurface,0);
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            USBCamera.nativeStopPreview(mSurface);
            mSurface = null;
        }
    };
}